package com.cf.game.node;

import com.cf.util.ObjectJsonUtil;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * boot-awm-NodeService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/27 上午 10:34
 */
public class NodeService {

    @Autowired
    private ZkClient zkClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String userKey = "user-node-";

    private Random random = new Random();

    /**
     * 注册节点
     *
     * @param node
     * @param pressure
     * @return 节点对应的nodeNum
     */
    public String registerNode(Node node, Pressure pressure) {
        String[] split = node.getParentPath().split("/");
        String path = "";
        for (String pathItem : split) {
            if (StringUtils.isEmpty(pathItem))
                continue;
            path = path + "/" + pathItem;
            this.createDirectory(path);
        }
        //创建的是临时的自增节点
        return zkClient.create(node.getPath(), ObjectJsonUtil.toString(pressure), CreateMode.EPHEMERAL_SEQUENTIAL).replace(node.getParentPath() + "/", "");
    }

    /**
     * 创建目录使用
     *
     * @param path
     * @return
     */
    public void createDirectory(String path) {
        if (!zkClient.exists(path)) {
            zkClient.create(path, "", CreateMode.PERSISTENT);
        }
    }

    /**
     * 注册用户与node的关系
     *
     * @param userId
     * @param nodeNum
     * @return
     */
    public void registerUserWithNode(String userId, String nodeNum) {
        redisTemplate.opsForValue().set(userKey + userId, nodeNum);
    }

    /**
     * 更具用户Id获取用户所在的node
     *
     * @param userId
     * @return
     */
    public String getUserNode(String userId) {
        return redisTemplate.opsForValue().get(userKey + userId);
    }

    /**
     * 注册用户与node的关系
     *
     * @param userId
     * @param nodeNum
     * @return
     */
    public void registerUserWithNode(long userId, String nodeNum) {
        redisTemplate.opsForValue().set(userKey + userId, nodeNum);
    }

    /**
     * 更具用户Id获取用户所在的node
     *
     * @param userId
     * @return
     */
    public String getUserNode(long userId) {
        return redisTemplate.opsForValue().get(userKey + userId);
    }


    public String getSuitableNode(String talkParentPath) {
        List<String> children = zkClient.getChildren(talkParentPath);
        if (children != null && children.size() > 0)
            return children.get(random.nextInt(children.size()));
        return null;
    }

    /**
     * 删除用户与gate的对应关系
     *
     * @param userId
     */
    public void logout(long userId) {
        redisTemplate.delete(userKey + userId);
    }

    /**
     * 查看在线的用户
     *
     * @param userIds
     * @return
     */
    public Map<String, String> online(List<Long> userIds) {
        List<String> userKeys = userIds.stream().map(uId -> {
            return userKey + uId;
        }).collect(Collectors.toList());
        List<String> userGates = redisTemplate.opsForValue().multiGet(userKeys);

        Map map = new HashMap();
        for (int start = 0; start < userIds.size(); start++) {
            map.put(userIds.get(start), userGates.get(start) != null);
        }
        return map;
    }
}
